﻿using System;
using System.Xml.Linq;

namespace SharePhone.Search
{
    public enum QueryType
    {
        STRING,
        MSSQLFT
    }

    public class SearchRange
    {
        public int Count;
        public int StartAt;
    }

    public class QueryPacket
    {
        public bool EnableStemming;
        public bool IgnoreAllNoiseQuery;
        public bool ImplicitAndBehavior;
        public bool IncludeHighConfidenceResults;
        public bool IncludeRelevanceResult;
        public bool IncludeSpecialTermResults;
        public string Query;
        public QueryType QueryType;
        public bool TrimDuplicates;
        public SearchRange Range { get; set; }

        public override string ToString()
        {
            return BuildXML().ToString();
        }

        internal XElement BuildXML()
        {
            XName name = XName.Get("QueryPacket", "urn:Microsoft.Search.Query");
            var queryPacket = new XElement(name);
            var query = new XElement("Query");
            var queryId = new XElement("QueryId", Guid.NewGuid().ToString());
            query.Add(queryId);
            var supportedFormats = new XElement("SupportedFormats");
            var format = new XElement("Format", "urn:Microsoft.Search.Response.Document.Document");
            supportedFormats.Add(format);
            query.Add(supportedFormats);
            var queryContext = new XElement("Context");
            var queryText = new XElement("QueryText", Query);
            queryText.SetAttributeValue("language", "en");
            queryText.SetAttributeValue("type", QueryType.ToString());
            queryContext.Add(queryText);
            query.Add(queryContext);
            if (Range != null)
            {
                var range = new XElement("Range");
                var startAt = new XElement("StartAt", Range.StartAt);
                var count = new XElement("Count", Range.Count);
                range.Add(startAt);
                range.Add(count);
                query.Add(range);
            }
            query.Add(new XElement("EnableStemming", EnableStemming));
            query.Add(new XElement("TrimDuplicates", TrimDuplicates));
            query.Add(new XElement("IgnoreAllNoiseQuery", IgnoreAllNoiseQuery));
            query.Add(new XElement("ImplicitAndBehavior", ImplicitAndBehavior));
            query.Add(new XElement("IncludeRelevanceResult", IncludeRelevanceResult));
            query.Add(new XElement("IncludeSpecialTermResults", IncludeSpecialTermResults));
            query.Add(new XElement("IncludeHighConfidenceResults", IncludeHighConfidenceResults));
            queryPacket.Add(query);
            return queryPacket;
        }
    }
}